package com.nativetalk.service.live.insert;

import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.FoundChange.TdNtMembFoundChangeInset;
import com.nativetalk.bean.coupon.TdNtCouponDetail;
import com.nativetalk.bean.live.*;
import com.nativetalk.bean.live.his.TdNtLiveCourseHisRecording;
import com.nativetalk.bean.member.TdNtMemberInvite;
import com.nativetalk.bean.reserve.TdNtReserveInsert;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.oss.OssUtil;
import com.nativetalk.common.util.CommonUtil;
import com.nativetalk.dao.*;
import com.pingplusplus.Pingpp;
import com.pingplusplus.model.Charge;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.InputFormatException;
import it.sauronsoftware.jave.MultimediaInfo;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by lizhun on 16/5/11.
 */
@Service
public class LiveInsertServiceimpl implements LiveInsertService {
    private static Logger logger = Logger.getLogger(LiveInsertServiceimpl.class);

    private static String recordingStorePath = Constants.FILE + "/" + Constants.FILEIMG + "/livecourse/recording";
    @Resource
    private TdNtLiveCourseDao tdNtLiveCourseDao;
    @Resource
    private TdNtLivePictureDao tdNtLivePictureDao;
    @Resource
    private TdNtLiveCourseHisDao tdNtLiveCourseHisDao;
    @Resource
    private TdNtLiveStudyDao tdNtLiveStudyDao;
    @Resource
    private TdNtMembFoundChangeDao tdNtMembFoundChangeDao;
    @Resource
    private TdNtMemberDao tdNtMemberDao;
    @Resource
    private TdNtCouponDao tdNtCouponDao;
    @Resource
    private TdNtReserveDao tdNtReserveDao;
    @Resource
    private TdNtLiveCourseHisRecordingDao tdNtLiveCourseHisRecordingDao;

    @Override
    public RetInfo addLiveHis(int live_cou_id, Timestamp timestamp) {
        String logInfo = this.getClass().getName() + ":addLiveHis:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();

        /**
         * 根据直播课程id查找直播课程
         */
        TdNtLiveCourseDetail tdNtLiveCourseDetail = tdNtLiveCourseDao.findTdNtLiveCourseDetail(live_cou_id);
        /**
         * 判断直播课程是否存在且已经审核通过
         */
        if (tdNtLiveCourseDetail != null && tdNtLiveCourseDetail.getLive_cou_state().equals("2")) {
            /**
             * 查找该老师是否有冲突时间的直播
             */
            Map<String, Object> map = new HashMap<>();
            map.put("tea_id", tdNtLiveCourseDetail.getTea_id());
            map.put("start_time", timestamp);
            map.put("end_time", new Timestamp(timestamp.getTime() + tdNtLiveCourseDetail.getLive_cou_time() * 60 * 1000));
            TdNtLiveCourseHisDetail live = tdNtLiveCourseHisDao.findTdNtLiveCourseHisDetailConflict(map);
            if (live != null) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("Conflicting time -- please select another time");
            } else {
                TdNtReserveInsert tdNtReserveInsert = tdNtReserveDao.findTdNtReserverConflict(map);
                if (tdNtReserveInsert != null) {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip("Conflicting time -- please select another time");
                }
                /**
                 * 添加直播
                 */
                TdNtLiveCourseHisInsert tdNtLiveCourseHisInsert = new TdNtLiveCourseHisInsert();
                tdNtLiveCourseHisInsert.setLive_channel(CommonUtil.getLiveChannel());
                tdNtLiveCourseHisInsert.setLive_cou_amount(tdNtLiveCourseDetail.getLive_cou_amount());
                tdNtLiveCourseHisInsert.setLive_cou_his_end_time(
                        new Timestamp(timestamp.getTime() + tdNtLiveCourseDetail.getLive_cou_time() * 60 * 1000));
                if (null != tdNtLiveCourseDetail.getLive_cou_system_name()) {
                    tdNtLiveCourseHisInsert.setLive_cou_his_name(tdNtLiveCourseDetail.getLive_cou_system_name());
                } else {
                    tdNtLiveCourseHisInsert.setLive_cou_his_name(tdNtLiveCourseDetail.getLive_cou_name());
                }
                if (tdNtLiveCourseDetail.getCover_system() != null) {
                    tdNtLiveCourseHisInsert.setLive_cou_his_picture(tdNtLiveCourseDetail.getCover_system());
                } else {
                    tdNtLiveCourseHisInsert.setLive_cou_his_picture(tdNtLiveCourseDetail.getCover());
                }
                tdNtLiveCourseHisInsert.setLive_cou_his_time(timestamp);
                tdNtLiveCourseHisInsert.setLive_cou_id(tdNtLiveCourseDetail.getLive_cou_id());
                tdNtLiveCourseHisInsert.setLive_cou_size(0);
                tdNtLiveCourseHisInsert.setLive_cou_state("1");
                tdNtLiveCourseHisInsert.setLive_cou_synopsis(tdNtLiveCourseDetail.getLive_cou_synopsis());
                tdNtLiveCourseHisInsert.setLive_cou_system_amount(tdNtLiveCourseDetail.getLive_cou_system_amount());
                tdNtLiveCourseHisInsert.setLive_cou_time(tdNtLiveCourseDetail.getLive_cou_time());
                tdNtLiveCourseHisInsert.setTea_id(tdNtLiveCourseDetail.getTea_id());
                tdNtLiveCourseHisInsert.setDict_id(tdNtLiveCourseDetail.getDict_id());
                tdNtLiveCourseHisInsert.setLive_label(tdNtLiveCourseDetail.getLive_label());
                tdNtLiveCourseHisDao.insertTdNtLiveCourseHis(tdNtLiveCourseHisInsert);
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("Successfully added a live stream");
            }

        } else {
            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
            retInfo.setTip("Live course does not exist or has not been approved");
        }

        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo addLiveCoursePicture(int live_cou_id, int tea_id, CommonsMultipartFile[] pictures) {
        String logInfo = this.getClass().getName() + ":addLiveCoursePicture:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();

        try {
            Integer pictures_size = tdNtLivePictureDao.findTdNtLivePictureByLiveIdSize(live_cou_id);
            /**
             * 查找直播图片数量
             */
            if (pictures.length >= (50 - pictures_size)) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setObj("No more than 50 pictures");
            } else {
                /**
                 * 查找图片最后一张的排序
                 */
                Integer max_sort = tdNtLivePictureDao.findTdNtLivePictureByLiveIdMaxSort(live_cou_id);
                /**
                 * 上传图片 添加图片
                 */
                for (int i = 0; i < pictures.length; i++) {

                    if (!pictures[i].isEmpty()) {
                        ObjectMetadata objectMetadata_picture = new ObjectMetadata();
                        objectMetadata_picture.setContentLength(pictures[i].getSize());
                        String picture = Constants.FILE + "/" + Constants.FILEIMG + "/image/teacher/live/" + tea_id
                                + "/" + live_cou_id + "/"
                                + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis()))
                                + i + pictures[i].getOriginalFilename().substring(pictures[i].getOriginalFilename().lastIndexOf("."));
                        OssUtil.uploadInputStream(pictures[i].getInputStream(), objectMetadata_picture, picture);
                        TdNtLivePictureInsert tdNtLivePictureInsert = new TdNtLivePictureInsert();
                        tdNtLivePictureInsert.setImg_sort(i + max_sort);
                        tdNtLivePictureInsert.setImg_url(picture);
                        tdNtLivePictureInsert.setIs_valid(0);
                        tdNtLivePictureInsert.setLive_cou_id(live_cou_id);
                        tdNtLivePictureDao.insertTdNtLivePicture(tdNtLivePictureInsert);
                    }
                }
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setObj("添加成功");
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo addLiveCourse(TdNtLiveCourseInsert tdNtLiveCourseInsert, CommonsMultipartFile[] pictures, CommonsMultipartFile cover) {
        String logInfo = this.getClass().getName() + ":addLiveCourse:";
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = new RetInfo();

        try {
            if (pictures.length >= 50) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setObj("No more than 50 pictures");
            } else {
                /**
                 * 上传封面图片
                 */
                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setContentLength(cover.getSize());
                String cover_src = Constants.FILE + "/" + Constants.FILEIMG + "/image/teacher/live/" + tdNtLiveCourseInsert.getTea_id() + "/cover/"
                        + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis())) + "2" + cover.getOriginalFilename().substring(cover.getOriginalFilename().lastIndexOf("."));
                OssUtil.uploadInputStream(cover.getInputStream(), objectMetadata, cover_src);
                /**
                 * 添加直播课程
                 */
                tdNtLiveCourseInsert.setCover(cover_src);
                tdNtLiveCourseInsert.setLive_cou_state("1");
                tdNtLiveCourseInsert.setAuh_month(CommonUtil.getMonth(now));

                tdNtLiveCourseDao.insertTdNtLiveCourse(tdNtLiveCourseInsert);
                /**
                 * 上传图片 添加图片
                 */
                for (int i = 0; i < pictures.length; i++) {

                    if (!pictures[i].isEmpty()) {
                        ObjectMetadata objectMetadata_picture = new ObjectMetadata();
                        objectMetadata_picture.setContentLength(pictures[i].getSize());
                        String picture = Constants.FILE + "/" + Constants.FILEIMG + "/image/teacher/live/" + tdNtLiveCourseInsert.getTea_id()
                                + "/" + tdNtLiveCourseInsert.getLive_cou_id() + "/"
                                + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis()))
                                + i + pictures[i].getOriginalFilename().substring(pictures[i].getOriginalFilename().lastIndexOf("."));
                        OssUtil.uploadInputStream(pictures[i].getInputStream(), objectMetadata_picture, picture);
                        TdNtLivePictureInsert tdNtLivePictureInsert = new TdNtLivePictureInsert();
                        tdNtLivePictureInsert.setImg_sort(i);
                        tdNtLivePictureInsert.setImg_url(picture);
                        tdNtLivePictureInsert.setIs_valid(0);
                        tdNtLivePictureInsert.setLive_cou_id(tdNtLiveCourseInsert.getLive_cou_id());
                        tdNtLivePictureDao.insertTdNtLivePicture(tdNtLivePictureInsert);
                    }
                }
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("添加成功");
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo transferBuy(Integer memb_id, Float amount, String ip, String channel) {
        String logInfo = this.getClass().getName() + ":transferBuy:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            Pingpp.apiKey = Constants.Live_Secret_Key;
            Map<String, Object> chargeParams = new HashMap<>();
            chargeParams.put("order_no", CommonUtil.getOrderNub());
            //chargeParams.put("amount", amount*100);  //单位为分
            chargeParams.put("amount", 1);  //单位为分，仅在测试的时候使用，否则请注释掉
            Map<String, String> app = new HashMap<String, String>();
            app.put("id", Constants.APP_ID);
            chargeParams.put("app", app);
            chargeParams.put("channel", channel);  //微信wx
            chargeParams.put("currency", "cny");
            chargeParams.put("client_ip", ip);
            chargeParams.put("subject", "购买直播课");
            chargeParams.put("body", "购买直播课");
            Charge charge = Charge.create(chargeParams);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("跳转成功");
            Map<String, Object> map = new HashMap<>();
            map.put("charge", charge);
            retInfo.setObj(map);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo addLive(TdNtLiveStudyInsert tdNtLiveStudyInsert, String channel, String userBlanace, String orderNo) {
        String logInfo = this.getClass().getName() + ":addLive:";
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = new RetInfo();
        try {
            TdNtLiveCourseHisDetails tdNtLiveCourseHisDetails = tdNtLiveCourseHisDao.findTdNtLiveCourseHisDetails(tdNtLiveStudyInsert.getLive_cou_his_id());
            /**
             * 判断直播是否可购买
             */
            if (tdNtLiveCourseHisDetails != null && !(tdNtLiveCourseHisDetails.getLive_cou_state().equals("3"))
                    && !(tdNtLiveCourseHisDetails.getLive_cou_state().equals("4"))) {
                /**
                 * 判断是否购买过该直播
                 */
                Map<String, Integer> params = new HashMap<>();
                params.put("memb_id", tdNtLiveStudyInsert.getMemb_id());
                params.put("live_cou_his_id", tdNtLiveStudyInsert.getLive_cou_his_id());
                TdNtLiveStudyDetail tdNtLiveStudyDetail = tdNtLiveStudyDao.findTdNtLiveStudyDetail(params);
                if (tdNtLiveStudyDetail != null) {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip("已购买该直播课");
                }
                //未购买该直播课
                else {
                    if (tdNtLiveCourseHisDetails.getLive_cou_system_amount().compareTo(new BigDecimal(0)) == 0) {
                        tdNtLiveStudyInsert.setState(Constants.PayState.success);
                    } else {
                        /**
                         * 判断用户是否有该直播优惠券
                         */
                        BigDecimal coupon_amount = new BigDecimal(0);
                        TdNtCouponDetail detail = new TdNtCouponDetail();
                        detail.setMemb_id(tdNtLiveStudyInsert.getMemb_id());
                        detail.setState(Constants.CouponState.unused);
                        detail.setType(Constants.CouponType.live);
                        detail.setLimit_id(tdNtLiveStudyInsert.getLive_cou_his_id());
                        TdNtCouponDetail couponDetail = tdNtCouponDao.findTdNtCouponDetail(detail);
                        if (couponDetail != null &&
                                (couponDetail.getCoupon_limit_amount().compareTo(new BigDecimal(0)) == 0
                                        || couponDetail.getCoupon_limit_amount().compareTo(tdNtLiveCourseHisDetails.getLive_cou_system_amount()) > -1)) {
                            coupon_amount = couponDetail.getCoupon_amount();
                            /**
                             * 更新优惠券
                             */
                            couponDetail.setState(Constants.CouponState.used);
                            tdNtCouponDao.updateTdNtCoupon(couponDetail);
                        }

                        BigDecimal change_amount = tdNtLiveCourseHisDetails.getLive_cou_system_amount().subtract(coupon_amount);
                        if (tdNtLiveCourseHisDetails.getLive_cou_system_amount().compareTo(coupon_amount) <= 0) {
                            tdNtLiveStudyInsert.setState(Constants.PayState.success);
                        } else {
                            /**
                             * 添加资金变动记录
                             */
                            TdNtMembFoundChangeInset tdNtMembFoundChangeInset;

                            int money_change_type;
                            String change_name;
                            if ("alipay".equals(channel)) {
                                //类型为支付宝支付
                                money_change_type = Constants.PaymentChannel.alipay;
                                change_name = "支付宝购买公开课";
                            } else if ("wx".equals(channel)) {
                                //类型为微信支付
                                money_change_type = Constants.PaymentChannel.wxpay;
                                change_name = "微信购买公开课";
                            } else {
                                money_change_type = Constants.PaymentChannel.wallet;
                                change_name = "购买公开课";
                            }

                            //判断是否使用余额 0表示使用余额
                            if (userBlanace.equals("0")) {
                                BigDecimal memb_balance = tdNtMemberDao.findTdNtMemberBalabce(tdNtLiveStudyInsert.getMemb_id());
                                TdNtMemberInvite tdNtMemberInvite = new TdNtMemberInvite();
                                //判断余额是否足够
                                if (memb_balance.compareTo(change_amount) > -1) {

                                    memb_balance = memb_balance.subtract(change_amount);
                                    tdNtMemberInvite.setMemb_balance(memb_balance);
                                    tdNtMemberInvite.setMemb_id(tdNtLiveStudyInsert.getMemb_id());

                                    tdNtMembFoundChangeInset = new TdNtMembFoundChangeInset();
                                    /**
                                     * 添加资金变动记录
                                     */
                                    tdNtMembFoundChangeInset.setMemb_id(tdNtLiveStudyInsert.getMemb_id());
                                    tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                                    tdNtMembFoundChangeInset.setMfchg_back_amount(memb_balance);
                                    tdNtMembFoundChangeInset.setMfchg_change_amount(change_amount);
                                    tdNtMembFoundChangeInset.setMfchg_change_name("购买公开课");
                                    tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                                    tdNtMembFoundChangeInset.setMfchg_front_amount(memb_balance.add(change_amount));
                                    tdNtMembFoundChangeInset.setState(Constants.PayState.success);
                                    tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_live_course_code);
                                    tdNtMembFoundChangeInset.setMfchg_number(CommonUtil.getOrderNub());

                                    tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);
                                    /**
                                     * 更新余额
                                     */
                                    tdNtMemberDao.updateTdNtMemberBalance(tdNtMemberInvite);
                                } else {
                                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                                    retInfo.setTip(ValidationMessages.getValue("MEMBBALANCE.NO"));
                                    return retInfo;
                                }

                            }
                            //使用第三方支付
                            else {
                                tdNtMembFoundChangeInset = tdNtMembFoundChangeDao.findTdNtMembFoundChangeByOrderNo(orderNo);
                                /**
                                 * notify异步先返回，该订单的记录已插入数据库
                                 */
                                if (null != tdNtMembFoundChangeInset) {
                                    //补全第三方支付的订单信息
                                    tdNtMembFoundChangeInset.setMemb_id(tdNtLiveStudyInsert.getMemb_id());
                                    tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                                    tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                                    tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_live_course_code);
                                    tdNtMembFoundChangeInset.setMoney_change_type(money_change_type);
                                    tdNtMembFoundChangeInset.setMfchg_change_name(change_name);
                                    tdNtMembFoundChangeDao.updatePaymentInfo(tdNtMembFoundChangeInset);
                                } else {
                                    tdNtMembFoundChangeInset = new TdNtMembFoundChangeInset();

                                    tdNtMembFoundChangeInset.setMemb_id(tdNtLiveStudyInsert.getMemb_id());
                                    tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                                    tdNtMembFoundChangeInset.setMfchg_change_amount(change_amount);
                                    tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                                    tdNtMembFoundChangeInset.setState(Constants.PayState.success);
                                    tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_live_course_code);
                                    tdNtMembFoundChangeInset.setMfchg_number(orderNo);
                                    tdNtMembFoundChangeInset.setMoney_change_type(money_change_type);
                                    tdNtMembFoundChangeInset.setMfchg_change_name(change_name);
                                    tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);
                                }
                            }

                            tdNtLiveStudyInsert.setState(Constants.PayState.success);
                            tdNtLiveStudyInsert.setMfchg_id(tdNtMembFoundChangeInset.getMfchg_id());
                        }

                    }

                    /**
                     * 添加直播
                     */
                    tdNtLiveStudyDao.addTdNtLiveStudyInsert(tdNtLiveStudyInsert);
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("购买直播课成功");
                }
            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("直播不可购买");
            }
            /**
             * 更新购买直播人数
             */
            TdNtLiveCourseHisInsert tdNtLiveCourseHisInsert = new TdNtLiveCourseHisInsert();
            tdNtLiveCourseHisInsert.setLive_cou_his_id(tdNtLiveCourseHisDetails.getLive_cou_his_id());
            tdNtLiveCourseHisInsert.setLive_cou_size(tdNtLiveCourseHisDetails.getLive_cou_size() + 1);
            tdNtLiveCourseHisDao.updateTdNtLiveCourseHisSize(tdNtLiveCourseHisInsert);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    /**
     * 保存直播课录音
     *
     * @param live_cou_his_id 直播课id
     * @param recordingFile   录音文件
     * @return
     */
    public RetInfo uploadLiveCourseHisRecording(int live_cou_his_id, CommonsMultipartFile recordingFile) {
        logger.info("====== uploadLiveCourseHisRecording  begin======");
        RetInfo retInfo = new RetInfo();

        try {
            //1. 上传图片到阿里云存储
            ObjectMetadata objectMetadata_picture = new ObjectMetadata();
            objectMetadata_picture.setContentLength(recordingFile.getSize());

            String month = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String suffix = recordingFile.getOriginalFilename().substring(recordingFile.getOriginalFilename().lastIndexOf("."));//文件后缀名(包含.)
            String pathname = recordingStorePath + "/" + month + "/" + "-" + UUID.randomUUID().toString() + suffix;
            OssUtil.uploadInputStream(recordingFile.getInputStream(), objectMetadata_picture, pathname);

            //获取音频时长，如果读取失败，设置音频时长为0
            long duration = 0;//音频时长，单位：秒
            DiskFileItem dfi = (DiskFileItem) recordingFile.getFileItem();
            File source = dfi.getStoreLocation();
            Encoder encoder = new Encoder();
            try {
                MultimediaInfo m = encoder.getInfo(source);
                long ls = m.getDuration();
                duration = ls / 1000;
            } catch (InputFormatException e) {
                logger.error("读取音频文件时长失败", e);
            } catch (EncoderException e) {
                logger.error("读取音频文件时长失败", e);
            }

            //2. 保存到数据库td_nt_live_course_his_recording表,app有可能会重复上传录音，如果该直播录音已经上传过了，就更新，否则新增
            Date now = new Date();
            TdNtLiveCourseHisRecording oldRecording = tdNtLiveCourseHisRecordingDao.findByLiveCouHisId(live_cou_his_id);
            if (oldRecording == null) {//新增
                TdNtLiveCourseHisRecording tdNtLiveCourseHisRecording = new TdNtLiveCourseHisRecording(live_cou_his_id, pathname, duration, recordingFile.getSize(), now, now);
                tdNtLiveCourseHisRecordingDao.insertTdNtLiveCourseHisRecording(tdNtLiveCourseHisRecording);
            } else {//更新
                oldRecording.setDuration(duration);
                oldRecording.setFile_size(recordingFile.getSize());
                oldRecording.setRecording_url(pathname);
                oldRecording.setUpdate_date(now);
                tdNtLiveCourseHisRecordingDao.update(oldRecording);
            }

            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("直播课录音上传成功");
            Map<String, Object> map = new HashMap<>();
            map.put("recording_url", pathname);
            retInfo.setObj(map);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR") + ",错误描述:" + e.getMessage());
        }
        return retInfo;

    }
}
